package com.tju.bclab.vote_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.tju.bclab.vote_backend.common.ResultCode;
import com.tju.bclab.vote_backend.entity.*;
import com.tju.bclab.vote_backend.exception.ApiException;
import com.tju.bclab.vote_backend.mapper.*;
import com.tju.bclab.vote_backend.service.VoteBlockChainService;
import com.tju.bclab.vote_backend.service.VoteService;
import com.tju.bclab.vote_backend.vo.req.AddVoteReq;
import com.tju.bclab.vote_backend.vo.resp.QueryVoteInfoResp;
import com.tju.bclab.vote_backend.vo.resp.VerifyHaveModified;
import com.tju.bclab.vote_backend.vo.resp.VoteRule;
import com.tju.bclab.vote_backend.service.OssService;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 投票表 服务实现类
 * </p>
 *
 * @author 张启航测试代码生成器
 * @since 2021-09-22
 */
@Service
public class VoteServiceImpl extends ServiceImpl<VoteMapper, Vote> implements VoteService {
    // 引入vote的mapper
    @Autowired
    private VoteMapper voteMapper;
    // 引入voteOption的mapper
    @Autowired
    private VoteOptionMapper voteOptionMapper;

    @Autowired
    private VotedescMapper votedescMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private VoteUserMapper voteUserMapper;

    @Autowired
    private VoteboxTimeMapper voteboxTimeMapper;

    @Autowired
    private selectedUserMapper selecteduserMapper;

    @Autowired
    private BlockChainServiceImpl blockChainService;

    @Autowired
    private VoteBlockChainService voteBlockChainService;

    @Autowired
    private VoteService voteService;

    @Autowired
    private OssService ossService;

    @Value("${pdf.path}")
    private String path;

    @Override
    public Set<String> qryJoinedVoteByUserId(String userId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("user_id", userId);
        List<VoteUser> votes = voteUserMapper.selectByMap(map);
        Set<String> result = new HashSet<String>();
        for (int i = 0; i < votes.size(); ++i) {
            Vote vote = voteMapper.selectById(votes.get(i).getVoteId());
            result.add(vote.getVoteId());
        }
        return result;
    }

    @Override
    public String qryTileByVoteId(String voteId) {
        Vote vote = qryVote(voteId);
        return vote.getTitle();
    }

    @Override
    public Vote qryVote(String voteId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("vote_id", voteId);
        List<Vote> votes = voteMapper.selectByMap(map);
        if (votes.size() == 0) {
            throw new ApiException(ResultCode.QUERY_FAILED);
        }
        Vote vote = votes.get(0);
        return vote;
    }

    @Override
    public QueryVoteInfoResp qryVote2(String voteId, String userId) {
        QueryVoteInfoResp queryVoteInfoResp = new QueryVoteInfoResp();
        // 获取投票
        Vote vote = voteMapper.selectById(voteId);

        // 获取投票发起人
        User sponsor = userMapper.selectById(vote.getUserId());
        // 获取投票图片
        Votedesc votedesc = votedescMapper.selectById(voteId);
        // 封装投票规则
        VoteRule voteRule = new VoteRule();
        voteRule.setVoteType(vote.getVoteType());
        voteRule.setType(vote.getType());
        voteRule.setDisplayOption(vote.getDisplayOption());
        voteRule.setEndDate(vote.getEndDate());
        voteRule.setNeedPersonalInformation(vote.getNeedPersonalInformation());
        voteRule.setDailyVote(vote.getDailyVote());
        voteRule.setShuffleOptions(vote.getShuffleOptions());
        voteRule.setOnlyGroupMember(vote.getOnlyGroupMember());
        voteRule.setIsAnonymous(vote.getIsAnonymous());

        QueryWrapper<VoteOption> optionQueryWrapper = new QueryWrapper<>();
        optionQueryWrapper.eq("vote_id", voteId);
        List<VoteOption> optionList = voteOptionMapper.selectList(optionQueryWrapper);

        QueryWrapper<VoteUser> voteQueryWrapper = new QueryWrapper<>();
        voteQueryWrapper.eq("vote_id", voteId);
        voteQueryWrapper.select("distinct user_id");
        List<VoteUser> voteUserList = voteUserMapper.selectList(voteQueryWrapper);

        List<String> voteAvatarUrls = new ArrayList<>();
        for (int i = 0; i < voteUserList.size(); i++) {
            User voter = userMapper.selectById(voteUserList.get(i).getUserId());
            voteAvatarUrls.add(voter.getAvatarUrl());
        }

        List<Float> markList = new ArrayList<>();

        Date curDate = new Date();
        Date endDate = vote.getEndDate();
        int count = curDate.compareTo(endDate);
        Boolean isExpired = count > 0 ? true : false;
        if (isExpired && vote.getKindOfVote() == 1) {
            if (voteUserList.size() <= 2 * vote.getN()) {
                for (int i = 0; i < optionList.size(); i++) {
                    if (optionList.get(i).getCount() == 0)// 尚且没有用户投这个选项
                        markList.add(0f);
                    else
                        markList.add(optionList.get(i).getTotalMark() / optionList.get(i).getCount());
                }
            } else {
                List<List<Float>> all_mark = new ArrayList<>();// 二维List记录每个用户对每个选项投票
                for (int i = 0; i < optionList.size(); i++) {
                    List<Float> xx = new ArrayList<>();
                    all_mark.add(xx);
                }
                for (int i = 0; i < voteUserList.size(); i++) {
                    QueryWrapper<VoteUser> personal_mark = new QueryWrapper<>();
                    personal_mark.eq("vote_id", voteId);
                    personal_mark.eq("user_id", voteUserList.get(i).getUserId());
                    List<VoteUser> personal_markList = voteUserMapper.selectList(personal_mark);
                    for (int j = 0; j < personal_markList.size(); j++) {
                        all_mark.get(j).add(personal_markList.get(j).getMark());
                    }
                }
                for (int i = 0; i < optionList.size(); i++) {
                    List<Float> yy = all_mark.get(i);
                    Collections.sort(yy);
                    Float total_n = optionList.get(i).getTotalMark();
                    for (int j = 0; j < vote.getN(); j++) {
                        total_n -= yy.get(j);
                        total_n -= yy.get(yy.size() - 1 - j);
                    }
                    markList.add(total_n / (optionList.get(i).getCount() - 2 * vote.getN()));
                }
            }
        } else if (!isExpired && vote.getKindOfVote() == 1) {
            QueryWrapper<VoteUser> user_markQueryWapper = new QueryWrapper<>();
            user_markQueryWapper.eq("vote_id", voteId);
            user_markQueryWapper.eq("user_id", userId);
            List<VoteUser> user_markList = voteUserMapper.selectList((user_markQueryWapper));
            for (int i = 0; i < user_markList.size(); i++)
                markList.add(user_markList.get(i).getMark());
        } else {
            for (int i = 0; i < optionList.size(); i++)
                markList.add(0f);
        }
        queryVoteInfoResp.setMarkList(markList);

        // 设置投票标题
        queryVoteInfoResp.setTitle(vote.getTitle());
        // 设置投票描述信息
        queryVoteInfoResp.setVoteDesc(vote.getVoteDesc());
        // 设置投票图片
        if (votedesc == null)
            queryVoteInfoResp.setDsecImgUrl("");
        else
            queryVoteInfoResp.setDsecImgUrl((votedesc.getImgUrl() == null) ? "" : votedesc.getImgUrl());
        // 设置投票选项
        queryVoteInfoResp.setOptionList(optionList);
        // 设置投票人头像
        queryVoteInfoResp.setVoteAvatarUrls(voteAvatarUrls);
        // 设置投票分享图片
        queryVoteInfoResp.setShareImgUrl((vote.getImgUrl() == null) ? "" : vote.getImgUrl());
        // 设置投票规则
        queryVoteInfoResp.setRule(voteRule);
        // 设置投票发起时间
        queryVoteInfoResp.setVoteCreate(vote.getGmtCreate());
        // 设置发起人头像
        queryVoteInfoResp.setSponsorAvatarUrl(sponsor.getAvatarUrl());
        // 设置发起人昵称
        queryVoteInfoResp.setNickName(sponsor.getNickName());
        // 设置投票人数
        queryVoteInfoResp.setSumUser(vote.getSumUser());
        // 设置至少可选
        queryVoteInfoResp.setLeastLimit(vote.getLeastLimit());
        // 设置至多可选
        queryVoteInfoResp.setMostLimit(vote.getMostLimit());

        // 设置openId
        queryVoteInfoResp.setOpenId(sponsor.getUserId());

        queryVoteInfoResp.setKindOfVote(vote.getKindOfVote());

        queryVoteInfoResp.setChooseVotersVote(vote.getChooseVotersVote());

        List<String> allow_id = new ArrayList<>();
        if (vote.getChooseVotersVote() == 1) {
            QueryWrapper<selectedUser> wrapper = new QueryWrapper<>();
            wrapper.eq("vote_id", voteId);
            List<selectedUser> selecteduser = selecteduserMapper.selectList(wrapper);
            for (int i = 0; i < selecteduser.size(); i++)
                allow_id.add(selecteduser.get(i).getUserId());
        }
        queryVoteInfoResp.setAllow_id(allow_id);

        return queryVoteInfoResp;
    }

    @Override
    public Set<String> qryVoteByUserId(String userId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("user_id", userId);
        List<Vote> votes = voteMapper.selectByMap(map);
        Set<String> result = new HashSet<String>();
        for (int i = 0; i < votes.size(); ++i) {
            Vote vote = votes.get(i);
            result.add(vote.getVoteId());
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String addVote(AddVoteReq addVoteReq) {// 传入的userid如果没在数据库中会报错

        System.out.println(addVoteReq);
        String id = addVoteReq.getUserId();
        User us = userMapper.selectById(id);

        // String uss = us.getPrivateKey();
        String privateKey = userMapper.selectById(id).getPrivateKey();

        // 存储投票表
        Vote vote = new Vote();
        BeanUtils.copyProperties(addVoteReq, vote);
        System.out.println(vote);
        int insert = voteMapper.insert(vote);
        // 如果insert小于0，则导入失败
        if (insert < 0) {
            throw new ApiException(ResultCode.STORE_FAILED);
        }

        if (vote.getChooseVotersVote() == 1) {
            // 存储选中用户
            ArrayList<String> userIdList = addVoteReq.getUserIdList();
            for (int i = 0; i < userIdList.size(); i++) {
                selectedUser selecteduser = new selectedUser();
                selecteduser.setUserId(userIdList.get(i));
                selecteduser.setVoteId(vote.getVoteId());
                int insert1 = selecteduserMapper.insert(selecteduser);
                if (insert1 < 0) {
                    throw new ApiException(ResultCode.STORE_FAILED);
                }
            }
            selectedUser selecteduser = new selectedUser();
            selecteduser.setUserId(vote.getUserId());
            selecteduser.setVoteId(vote.getVoteId());
            int insert2 = selecteduserMapper.insert(selecteduser);
            if (insert2 < 0) {
                throw new ApiException(ResultCode.STORE_FAILED);
            }
        }

        // 存储投票描述表
        ArrayList<String> descImgUrls = addVoteReq.getDescImgUrls();
        for (String descImgUrl : descImgUrls) {
            Votedesc votedesc = new Votedesc();
            votedesc.setVoteId(vote.getVoteId());
            votedesc.setImgUrl(descImgUrl);
            int insert1 = votedescMapper.insert(votedesc);
            if (insert1 < 0) {
                throw new ApiException(ResultCode.STORE_FAILED);
            }
        }

        // 存储选项表
        String voteId = vote.getVoteId();
        List<String> optionLists = addVoteReq.getOptionList();
        List<String> urls = addVoteReq.getUrls();
        System.out.println(optionLists);
        System.out.println(urls);
        for (int i = 0; i < optionLists.size(); i++) {
            String option = optionLists.get(i);
            String url = urls.get(i);
            VoteOption voteOption = new VoteOption()
                    .setOptionIndex(i)
                    .setOptionStr(option)
                    .setVoteId(voteId)
                    .setImgUrl(url)
                    .setTotalMark(0f);
            int flag = voteOptionMapper.insert(voteOption);
            if (flag < 0) {
                throw new ApiException(ResultCode.STORE_FAILED);
            }
            // 保存到区块链上
            String hash = makeHash(voteId);
            QueryWrapper<VoteOption> optionQueryWrapper = new QueryWrapper<>();
            // 获得optionId
            optionQueryWrapper.eq("vote_id", voteId);
            optionQueryWrapper.eq("option_index", i);
            List<VoteOption> optionList = voteOptionMapper.selectList(optionQueryWrapper);

            hash += optionList.get(0).getOptionId();
            try {
                VoteBlockChain voteBlockChain = blockChainService.VoteContract(hash, privateKey);
                // 上链后更新TransactionId字段
                Vote voteUpdate = voteMapper.selectById(voteId);
                voteUpdate.setTransactionId(voteBlockChain.getTransactionId());
                voteMapper.updateById(voteUpdate);
            } catch (Exception e) {
                throw new ApiException(ResultCode.CONTRACT_CALL_FAILED);
            }
        }
        return voteId;
    }

    @Override
    public String PrintResult(String voteId) throws Exception {
        File dir = new File(path);
        if (!dir.exists()) {
            File dir_ = new File(path.substring(0, path.length() - 1));
            dir_.mkdir();
        }

        QueryWrapper<VoteOption> voteOptionQueryWrapper = new QueryWrapper<>();
        voteOptionQueryWrapper.eq("vote_id", voteId);
        List<VoteOption> voteOptionList = voteOptionMapper.selectList(voteOptionQueryWrapper);

        int optionSum = voteOptionList.size();

        BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font font = new Font(baseFont, 12, Font.NORMAL);
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(path + voteId + ".pdf"));

        Vote vote = voteMapper.selectById(voteId);

        document.open();
        document.newPage();
        Paragraph title = new Paragraph(vote.getTitle(), font);
        title.setSpacingAfter(5); // 设置段落下空白
        title.setAlignment(Paragraph.ALIGN_CENTER); // 设置文字居中
        document.add(title);

        Paragraph des = new Paragraph(vote.getVoteDesc(), font);
        des.setSpacingAfter(5);
        des.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(des);

        Boolean isimgvote = false;
        String img_url = voteOptionList.get(0).getImgUrl();
        String xx = "https://tank-vote-img.oss-cn-beijing.aliyuncs.com/";
        Float scale = 0.2f;
        if (img_url.indexOf(xx) != -1) {
            isimgvote = true;

            File dir_ = new File(path + voteId);
            dir_.mkdir();

            for (int i = 0; i < optionSum; i++) {
                URL urlimg = new URL(voteOptionList.get(i).getImgUrl());

                URLConnection urlConnection = urlimg.openConnection();
                urlConnection.setConnectTimeout(1000);
                urlConnection.connect();

                BufferedImage bufferedImage = ImageIO.read(urlConnection.getInputStream());
                int width = (int) (bufferedImage.getWidth() * scale <= 200 ? bufferedImage.getWidth() * scale : 200);
                int height = (int) (bufferedImage.getHeight() * scale <= 200 ? bufferedImage.getHeight() * scale : 200);
                BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                tag.getGraphics().drawImage(bufferedImage, 0, 0, width, height, null);

                if (bufferedImage != null) {
                    File outputfile = new File(path + voteId + "/"
                            + voteOptionList.get(i).getOptionId() + ".jdg");
                    ImageIO.write(tag, "jpg", outputfile);
                }
            }
        }

        Boolean ismarkvote = false;
        List<Float> markList = new ArrayList<>();
        if (vote.getKindOfVote() == 1) {
            QueryWrapper<VoteOption> optionQueryWrapper = new QueryWrapper<>();
            optionQueryWrapper.eq("vote_id", voteId);
            List<VoteOption> optionList = voteOptionMapper.selectList(optionQueryWrapper);

            QueryWrapper<VoteUser> voteQueryWrapper = new QueryWrapper<>();
            voteQueryWrapper.eq("vote_id", voteId);
            voteQueryWrapper.select("distinct user_id");
            List<VoteUser> voteUserList = voteUserMapper.selectList(voteQueryWrapper);

            if (voteUserList.size() <= 2 * vote.getN()) {
                for (int i = 0; i < optionList.size(); i++) {
                    if (optionList.get(i).getCount() == 0)// 尚且没有用户投这个选项
                        markList.add(0f);
                    else
                        markList.add(optionList.get(i).getTotalMark() / optionList.get(i).getCount());
                }
            } else {
                List<List<Float>> all_mark = new ArrayList<>();// 二维List记录每个用户对每个选项投票
                for (int i = 0; i < optionList.size(); i++) {
                    List<Float> yy = new ArrayList<>();
                    all_mark.add(yy);
                }
                for (int i = 0; i < voteUserList.size(); i++) {
                    QueryWrapper<VoteUser> personal_mark = new QueryWrapper<>();
                    personal_mark.eq("vote_id", voteId);
                    personal_mark.eq("user_id", voteUserList.get(i).getUserId());
                    List<VoteUser> personal_markList = voteUserMapper.selectList(personal_mark);
                    for (int j = 0; j < personal_markList.size(); j++) {
                        all_mark.get(j).add(personal_markList.get(j).getMark());
                    }
                }
                for (int i = 0; i < optionList.size(); i++) {
                    List<Float> yy = all_mark.get(i);
                    Collections.sort(yy);
                    Float total_n = optionList.get(i).getTotalMark();
                    for (int j = 0; j < vote.getN(); j++) {
                        total_n -= yy.get(j);
                        total_n -= yy.get(yy.size() - 1 - j);
                    }
                    markList.add(total_n / (optionList.get(i).getCount() - 2 * vote.getN()));
                }
            }
            ismarkvote = true;
        }

        for (int i = 0; i < optionSum; i++) {
            if (isimgvote && i > 0 && i % 3 == 0) {
                document.newPage();
                document.add(title);
                document.add(des);
            }

            VoteOption voteOption = voteOptionList.get(i);

            String desc = voteOption.getOptionStr() == null ? "" : voteOption.getOptionStr();
            Paragraph optionDesc = new Paragraph(i + 1 + "、" + desc, font);
            optionDesc.setSpacingAfter(3);
            document.add(optionDesc);

            if (isimgvote) {
                Image img_des = Image.getInstance(path + voteId + "/"
                        + voteOption.getOptionId() + ".jdg");
                img_des.setAlignment(Image.MIDDLE);
                document.add(img_des);
            }

            if (ismarkvote) {
                Float total_mark = voteOption.getTotalMark();
                Paragraph option_totalmark = new Paragraph("    打分总和:  " + total_mark, font);
                option_totalmark.setSpacingAfter(3);
                document.add(option_totalmark);

                Float fin_mark = markList.get(i);
                Paragraph option_finmark = new Paragraph("    最终结果:  " + fin_mark, font);
                option_finmark.setSpacingAfter(3);
                document.add(option_finmark);
            } else {
                Integer count = voteOption.getCount();
                Paragraph optioncount = new Paragraph("    投票人数:  " + count, font);
                optioncount.setSpacingAfter(3);
                document.add(optioncount);
            }

        }

        document.close();

        FileItem fileItem = createFileItem(path + voteId + ".pdf");
        MultipartFile mfile = new CommonsMultipartFile(fileItem);
        String url = ossService.uploadPdf(mfile);
        // FileUtils.deleteDirectory(new File(path + voteId));

        return url;
    }

    public FileItem createFileItem(String filePath) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String textFieldName = "textField";
        int num = filePath.lastIndexOf(".");
        FileItem item = factory.createItem(textFieldName, "text/plain", true, "MyFileName");
        File newfile = new File(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(newfile);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

    public List<VerifyHaveModified> verifyVote(String voteId) throws Exception {
        Vote vote = voteService.qryVote(voteId);
        VoteBlockChain voteBlockChain = voteBlockChainService.qryByTransactionId(vote.getTransactionId());
        Long blockHeight = voteBlockChain.getBlockHeight();
        List<VerifyHaveModified> hashArr = blockChainService.voteVerify(blockHeight);
        List<VerifyHaveModified> result = compareHash(hashArr);
        return result;
    }

    @Override
    public List<User> GetUserInfo(String userId) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.ne("user_id", userId);
        List<User> userList = userMapper.selectList(userQueryWrapper);

        return userList;
    }

    @Override
    public List<User> searchnotvote(String voteId) {
        QueryWrapper<VoteUser> voteuserWrapper = new QueryWrapper<>();
        voteuserWrapper.eq("vote_id", voteId);
        List<VoteUser> voteuserList = voteUserMapper.selectList(voteuserWrapper);
        List<String> voted = new ArrayList<>();
        for (int i = 0; i < voteuserList.size(); i++)
            voted.add(voteuserList.get(i).getUserId());

        QueryWrapper<selectedUser> selecteduserWrapper = new QueryWrapper<>();
        selecteduserWrapper.eq("vote_id", voteId);
        List<selectedUser> selecteduserList = selecteduserMapper.selectList(selecteduserWrapper);
        List<String> all = new ArrayList<>();
        for (int i = 0; i < selecteduserList.size(); i++)
            all.add(selecteduserList.get(i).getUserId());

        // List<String> not_vote = all.stream().filter(item ->
        // !voted.contains(item)).collect(Collectors.toList());

        List<String> not_vote = all;
        not_vote.removeAll(voted);

        List<User> result = new ArrayList<>();
        for (int i = 0; i < not_vote.size(); i++) {
            User user = userMapper.selectById(not_vote.get(i));
            result.add(user);
        }
        return result;
    }

    public List<VerifyHaveModified> compareHash(List<VerifyHaveModified> hashlist) {

        for (int i = 0; i < hashlist.size(); i++) {
            int record = 0;
            for (int j = 0; j < hashlist.size(); j++) {
                if (hashlist.get(i).getBlockHash().equals(hashlist.get(j).getBlockHash())) {
                    record++;
                }
            }
            hashlist.get(i).setCountRecord(record);
        }
        for (int k = 0; k < hashlist.size(); k++) {
            if (hashlist.get(k).getCountRecord() < 3)
                hashlist.get(k).setHaveModified(true);
            else
                hashlist.get(k).setHaveModified(false);
        }
        return hashlist;

    }

    @Override
    public Boolean dailyVote(String voteId) {
        Vote vote = voteMapper.selectById(voteId);
        int dailyVote = vote.getDailyVote();
        if (dailyVote == 1)
            return true;// 是每日一投
        else
            return false;
    }

    @Override
    public Date getEndVoteDate(String voteId) {
        Vote vote = voteMapper.selectById(voteId);
        return vote.getEndDate();
    }

    /**
     * 判断投票箱投票是否已经超过当前开始时间
     *
     * @param voteId
     * @return {@link Boolean}
     * @author Zhang QiHang.
     * @date 2021/12/22 20:06
     */
    @Override
    public Boolean afterStartTime(String voteId) {
        QueryWrapper<VoteboxTime> voteboxTimeQueryWrapper = new QueryWrapper<>();
        voteboxTimeQueryWrapper.eq("vote_id", voteId);
        List<VoteboxTime> voteboxTimeList = voteboxTimeMapper.selectList(voteboxTimeQueryWrapper);
        if (voteboxTimeList.size() != 0) {
            Date startTime = voteboxTimeList.get(0).getPlanStartTime();
            Date nowTime = new Date();
            if (nowTime.after(startTime)) {
                return true;
            }
        }
        return false;
    }

    public String makeHash(String voteId) {
        Vote vote = voteMapper.selectById(voteId);
        String string = voteId;
        string = string + vote.getUserId() + vote.getTitle() + vote.getVoteDesc() + vote.getType().toString()
                + vote.getGmtCreate().toString()
                + vote.getIsAnonymous().toString() + vote.getEndDate().toString() + vote.getVoteType().toString()
                + vote.getShuffleOptions().toString()
                + vote.getDailyVote().toString() + vote.getNeedPersonalInformation().toString()
                + vote.getDisplayOption().toString();
        return string;
    }
}
